<?php slot("page", "addSource"); ?>

<?php
    if ($sf_user->hasFlash("addInfo")) {
        echo "<div class='alert alert-info'>" . $sf_user->getFlash("addInfo") . "</div>";
    }
    else if ($addingFirstSource) {
        echo "<div class='alert alert-info'>Before we can start collecting your users' feedback, we need to set up some app sources to retrieve feedback for. Use the search
                below to add a number of sources.</div>";
    }
?>

<div class="row">
    <div class="span12" id="source-new">
                
        <?php if ($user->isAllowedToAddMoreSources()): ?>
            <div class="tabbable well">
                <ul class="nav nav-tabs">
                    <li class="active"><a href="#app-store-source" data-toggle="tab"><img src="/img/icon-app-store.png" /> <span class="tab-title">App Store</span></a></li>
                    <li><a href="#google-play-source" data-toggle="tab"><img src="/img/icon-google-play.png" /> <span class="tab-title">Google Play</span></a></li>
                    <li><a href="#twitter-source" data-toggle="tab"><img src="/img/icon-twitter.png" /> <span class="tab-title">Twitter</span></a></li>
                </ul>
                <div class="tab-content">
                    <div class="tab-pane active" id="app-store-source">
                        <div class="form-search">
                            <input type="text" class="input-large search-query" placeholder="Search the App Store" />
                            <select>
                                <?php
                                    foreach (Config::$countries as $countryCode => $countryConfig) {
                                        echo "<option value='" . $countryCode . "'>" . $countryConfig["name"] . "</option>";
                                    }
                                ?>
                            </select>
                            <button class="btn search-submit">Search</button>
                        </div>
                        <div class="spacer" style="height: 15px;"></div>
                        <p class="help-block">Use the search to find your app in the app store. Then click "Add" to add this source to your <strong>Fydal</strong>.</p>
                    </div>
                    <div class="tab-pane" id="google-play-source">
                        <div class="form-search">
                            <input type="text" class="input-large search-query" placeholder="Search Google Play" />
                            <button class="btn search-submit">Search</button>
                        </div>
                        <div class="spacer" style="height: 15px;"></div>
                        <p class="help-block">Use the search to find your app in Google Play. Then click "Add" to add this source to your <strong>Fydal</strong>.</p>
                    </div>
                    <div class="tab-pane" id="twitter-source">
                        <div class="form-search">
                            <input type="text" class="input-large search-query" placeholder="Test Twitter search term" />
                            <button class="btn search-submit">Search</button>
                            <button class="btn btn-primary" id="add-twitter-source">Add this search term as a new source</button>
                        </div>
                        <div class="spacer" style="height: 15px;"></div>
                        <p class="help-block">Use the search to test your Twitter search terms. Once you're satisfied that the search term is bringing back the right results,
                            then click "Add this search term as a new source" to add this source to your <strong>Fydal</strong>.</p>
                        <p class="help-block">
                            (<strong>Hint</strong>: to use multiple search terms, try using search operators e.g. "gmail OR (google mail)".
                            More details about search operators can be found in the <a href="https://dev.twitter.com/docs/using-search" target="_blank">Twitter search API documentation</a>.
                            This is recommended to avoid different searches bringing back duplicate tweets.)
                        </p>
                    </div>
                </div>
            </div>
        <?php else: ?>
            <div class="alert alert-info">You have reached your maximum number of allowed sources. Please see the <a href="<?php echo url_for("home/help") ?>#sources">help</a> page for more information about how to upgrade your account to add extra sources.</div>
        <?php endif; ?>
        
    </div>
</div>

<div id="results"></div>

<!-- Source added modal -->
<div class="modal hide fade" id="source-added-modal" style="margin-top: -200px;">
    <div class="modal-header">
        <h3><i class="icon-ok"></i> Your source has been added</h3>
    </div>
    <div class="modal-body main">
        <p>The selected source has now been added to your Fydal. You will see this source on your dashboard.</p>
        <p>Before you can start using your new source, it will need to be updated. You will see the updates status bar appear at the bottom of your screen.
            It will show the progress of your updates, and notify you when your update is complete. Please be patient - you'll be recieving feedback and
            learning about your customers in no time!</p>
    </div>
    <div class="modal-footer">
        <button class="btn" id="source-added-go-to-dash">Return to the dashboard</button>
        <button class="btn btn-primary" id="source-added-add-another">Add another source</button>
    </div>
</div>

<script type="text/javascript">
    
    $(document).ready(function() {
        
        $("#source-added-go-to-dash").click(function() {
            window.location.href = "<?php echo url_for('feedback/index') ?>";
        });
        $("#source-added-add-another").click(function() {
            window.location.href = "<?php echo url_for('feedback/addSource') ?>";
        });
        
        // For doing the actual source add
        
        var callAddSource = function(providerName, appConfig) {
            
            $("#main").mask("Adding...");
            
            var url = "<?php echo url_for('feedback/doAddSource') ?>?provider=" + providerName;
            $.each(appConfig, function(index, element) {
                url += "&" + index + "=" + encodeURIComponent(element);
            });
            
            $.getJSON(
                url,
                function(data) {
                    
                    if (data.success) {
                        $("#source-added-modal").modal();
                    }
                    else {
                        $("#main").unmask();
                        
                        // TODO error handling
                    }
                }
            );
        }
        
        // For each of the search result components
        
        var addSourceSearchComponent = function(id, providerName, baseUrl, createAppResult, resultsPerRow) {
            var doSearch = function() {
                var text = $("#" + id + " input.search-query").val();
                var countryCode = $("#" + id + " select").val(); // App store has this, Google Play doesn't
                if (text) {
                    $("#results").empty();
                    
                    $("#source-new").mask("Searching...");
                    
                    var url = baseUrl + "?text=" + encodeURIComponent(text);
                    if (countryCode) {
                        url += "&country=" + countryCode;
                    }
                    
                    $.getJSON(
                        url,
                        function(data) {
                            
                            $("#source-new").unmask();
                            
                            if (data.success) {
                                if (data.results.length > 0) {
                                    var results = [];
                                    $(data.results).each(function(index, element) {
                                        results.push(createAppResult(providerName, element, countryCode));
                                    });
                                    
                                    var count = 0;
                                    var currentRow = $("<div />").addClass("row").appendTo("#results");
                                    $(results).each(function(index, element) {
                                        count++;
                                        if (count > resultsPerRow) {
                                            currentRow = $("<div />").addClass("row").appendTo("#results");
                                            count = 1;
                                        }
                                        
                                        $(currentRow).append(element);
                                    });
                                }
                                else {
                                    $("<div />")
                                        .addClass("results")
                                        .addClass("alert")
                                        .addClass("alert-info")
                                        .html("Sorry, no results were found. Please review your search criteria.")
                                        .appendTo("#results");
                                }
                            }
                            else {
                                // TODO error
                            }
                        }
                    );
                    
                }
            };
            
            $("#" + id + " button.search-submit").click(doSearch);
            
            $("#" + id + " input.search-query").keyup(function(e) {
                if ($(this).val()) {
                    $("#" + id + " button.search-submit").removeClass("disabled");
                }
                else {
                    $("#" + id + " button.search-submit").addClass("disabled");
                }
                
                if (e.which == 13) {
                    doSearch();
                }
            });
            $("#" + id + " button.search-submit").addClass("disabled");
        };
        
        // Add each of the searches (using a common function for the apps)
        
        var createAppResult = function(providerName, data, countryCode) {
            return $("<div />")
                .addClass("span4")
                .append(
                    $("<div />")
                        .addClass("well")
                        .addClass("source")
                        .append(
                            $("<span />")
                                .addClass("source-icon")
                                .append(
                                    $("<img />").attr("src", data.icon)
                                )
                        )
                        .append(
                            $("<h3 />").html(data.name)
                        )
                        .append(
                            $("<span />")
                                .addClass("publisher")
                                .html("by " + data.name)
                        )
                        .append($("<div />").addClass("clear"))
                        .append(
                            $("<div />")
                                .addClass("buttons")
                                .append(
                                    $("<button />")
                                        .addClass("btn")
                                        .addClass("btn-primary")
                                        .html("Add")
                                        .click(function() {
                                            var appConfig = {
                                                id: data.id
                                            };
                                            if (countryCode) {
                                                appConfig.country = countryCode;
                                            }
                                            callAddSource(providerName, appConfig);
                                        })
                                )
                        )
                );
        };
        
        addSourceSearchComponent(
            "app-store-source",
            "itunes",
            "<?php echo url_for('feedback/searchAppStore') ?>",
            createAppResult,
            3
        );
        
        addSourceSearchComponent(
            "google-play-source",
            "play",
            "<?php echo url_for('feedback/searchGooglePlay') ?>",
            createAppResult,
            3
        );
        
        addSourceSearchComponent(
            "twitter-source",
            "twitter",
            "<?php echo url_for('feedback/searchTwitter') ?>",
            function(providerName, data) {
                return $("<div />")
                    .addClass("span6")
                    .append(
                        $("<div />")
                            .addClass("well")
                            .addClass("twitter-result")
                            .append(
                                $("<img />")
                                    .attr("src", data.avatar)
                                    .addClass("avatar")
                            )
                            .append(
                                $("<div />").html("<p><strong>" + data.user + ":</strong></p><p>" + data.tweet + "</p>")
                            )
                    );
            },
            2
        );
        
        // Support the button for adding Twitter searches
        
        $("#add-twitter-source").click(function() {
            var text = $("#twitter-source input.search-query").val();
            if (text) {
                callAddSource("twitter", {term: text});
            }
        });
        
        $("#twitter-source input.search-query").keyup(function() {
            if ($(this).val()) {
                $("#add-twitter-source").removeClass("disabled");
            }
            else {
                $("#add-twitter-source").addClass("disabled");
            }
        });
        $("#add-twitter-source").addClass("disabled");
    });
    
</script>
